package xyz.scootaloo.kami.cloud.lang

import io.vertx.core.Future
import io.vertx.core.Future.succeededFuture
import io.vertx.core.json.JsonObject
import xyz.scootaloo.kami.cloud.model.po.ServiceResult

/**
 * @author flutterdash@qq.com
 * @since 2022/4/10 15:39
 */
@Public
object Bus {

    fun publish(address: String, message: Any) {
        Global.eventbus().publish(address, message)
    }

    fun send(address: String, message: Any) {
        Global.eventbus().send(address, message)
    }

    inline fun <reified T : Any> callService(address: String, arg: Any): Future<ServiceResult<T>> {
        return Global.eventbus().request<JsonObject>(address, arg).compose { response ->
            val json = response.body()
            val result = ServiceResult.deserialize<T>(json)
            succeededFuture(result)
        }
    }

    @JvmName("requestString")
    fun  request(address: String, message: Any): Future<String?> {
        return Global.eventbus().request<String>(address, message).compose {
            succeededFuture<String>(it.body())
        }
    }

    @JvmName("requestObject")
    inline fun <reified T : JsonSerializable> request(address: String, message: Any): Future<T?> {
        return Global.eventbus().request<JsonObject>(address, message).compose { response ->
            val json = response.body() ?: return@compose succeededFuture(null)
            val result = deserializer<T>(json)
            succeededFuture<T>(result)
        }
    }

}